package b1.mobile.blackberry.io.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;

import javax.microedition.io.*;

import net.rim.device.api.io.http.*;
import net.rim.device.api.io.transport.ConnectionDescriptor;
import net.rim.device.api.io.transport.ConnectionFactory;
import net.rim.device.api.io.transport.TransportInfo;


public class Serviceworker implements Runnable{	
	public static String session_id = null;
	
	public interface ServiceDelegate {
		void onGetResult(Serviceworker worker);
	}
	
	int[] preferredTransportTypes = {TransportInfo.TRANSPORT_TCP_WIFI
			, TransportInfo.TRANSPORT_TCP_CELLULAR
			, TransportInfo.TRANSPORT_WAP2
			, TransportInfo.TRANSPORT_WAP};
	
	private ConnectionFactory factory = new ConnectionFactory();
	private ConnectionDescriptor connDescriptor;
	private HttpConnection httpConn;
	private ServiceDelegate delegate;
	private SoapContentProvider contentProvider;
	
	public int responseCode;
	public String responseMessage;
	
	public Serviceworker(ServiceDelegate delegate, ServerInfo server, SoapContentProvider contentProvider) throws Exception{
		this.delegate = delegate;
//		this.server = server;
		this.factory.setPreferredTransportTypes(this.preferredTransportTypes);
		this.contentProvider = contentProvider;
		this.connDescriptor = factory.getConnection(server.getUrl());
		
		if(this.connDescriptor == null){
			throw new Exception("URL is invalid.");
		}
	}
	
	public String getOperator(){
		return contentProvider.getOperator();
	}
	
	public void run(){
		try {		
//			int transportUsed = connDescriptor.getTransportDescriptor().getTransportType();           
			this.httpConn = (HttpConnection)connDescriptor.getConnection();
			this.httpConn.setRequestMethod(HttpConnection.POST);		
			
			if(session_id != null){
				httpConn.setRequestProperty(HttpProtocolConstants.HEADER_COOKIE, session_id);
			}
			
			OutputStream os = httpConn.openOutputStream();
			os.write(this.contentProvider.getSoapMessage().getBytes());
			
			this.responseCode = httpConn.getResponseCode();
			
			// fetch the session id when log on
			if(this.responseCode == HttpConnection.HTTP_OK && httpConn.getHeaderField(HttpProtocolConstants.HEADER_SET_COOKIE) != null){
				session_id = httpConn.getHeaderField(HttpProtocolConstants.HEADER_SET_COOKIE);
			}
			
			InputStream is = httpConn.openInputStream();
			Reader reader = new java.io.InputStreamReader(is);
			char[] buf = new char[1024];
			try{
				int count = -1;
				StringBuffer writer = new StringBuffer();
				while((count = reader.read(buf)) != -1){
					writer.append(buf, 0, count);
				}				
				this.responseMessage = writer.toString();
				
			} finally {
				is.close();
				reader.close();
			}
			
			this.delegate.onGetResult(this);
			
		} catch (IOException e) {
				
		}
	}
}
